<template>
  <div>
    <HomeHeader />

    <van-tabs v-model="activeTab" sticky swipeable>
      <van-tab :title="category.name" v-for="category in categoriesList" :key="category.id">
        <van-list v-model="category.loading" :finished="category.finished" @load="loadMorePost" :immediate-check="false" finished-text="别再拉拉扯扯">
          <PostItem :postData="post" v-for="post in category.postList" :key="post.id" />
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import HomeHeader from '../components/HomeHeader'
import PostItem from '../components/PostItem'
export default {
  components: {
    HomeHeader,
    PostItem
  },
  data() {
    return {
      activeTab: 0,
      categoriesList: []
    }
  },
  created() {
    this.getCategories()
  },
  computed: {
    categoryId() {
      const currentCategory = this.categoriesList[this.activeTab]
      console.log(currentCategory)

      return currentCategory.id
    }
  },
  watch: {
    activeTab() {
      const currentCategory = this.categoriesList[this.activeTab]
      if (currentCategory.postList.length === 0) {
        this.getPost()
      }
      // this.getPost()
      // console.log(this.activeTab)
    }
  },
  methods: {
    getCategories() {
      this.$axios({
        url: '/category'
      }).then(res => {
        console.log(res.data)
        // this.categoriesList = res.data.data
        const newData = res.data.data.map(category => {
          return {
            ...category,
            postList: [],
            pageIndex: 1,
            pageSize: 5,
            loading: false,
            finished: false
          }
        })
        this.categoriesList = newData
        this.getPost()
      })
    },
    loadMorePost() {
      const currentCategory = this.categoriesList[this.activeTab]
      currentCategory.pageIndex += 1
      this.getPost()
    },
    getPost() {
      const currentCategory = this.categoriesList[this.activeTab]
      this.$axios({
        url: '/post',
        params: {
          category: this.categoryId,
          pageIndex: currentCategory.pageIndex,
          pageSize: currentCategory.pageSize
        }
      }).then(res => {
        console.log(res.data)
        currentCategory.postList = [...currentCategory.postList, ...res.data.data]

        currentCategory.loading = false
        if (res.data.data.length < currentCategory.pageSize) {
          currentCategory.finished = true
        }
        // this.postList = res.data.data
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
